import * as React from "react";
import classNames from "classnames/bind";
import * as styles from "./file-explorer-view.css";
import { IFilesState, IFile } from "../../core/model";
import { dispatch as appDispatch } from "../../core/app-state";

const cx = classNames.bind(styles);

function FolderView (props: { folder: IFile, level: number }) {
  const { folder, level } = props;
  const [ isExpand, setIsExpand ] = React.useState(false);
  const { children } = folder;

  const onClick = (e: React.MouseEvent) => {
    setIsExpand(!isExpand);
    if (!folder.isLoaded) {
      appDispatch({
        type: 'folder.load',
        data: folder,
      });
    }
  };

  return (
    <div className={cx('file-tree')}>
      <div className={cx('file-tree-name')} onClick={onClick} style={{paddingLeft: level * 16 + 5}}>
        <i className={ isExpand ? 'icon-folder-open' : 'icon-folder' } style={{marginRight: 3}}></i>
        <span>{folder.name}</span>
      </div>
      <div className={cx('file-tree-children', { 'is-show': isExpand })}>
        { children?.map(o => (
          o.isFolder ?
            <FolderView key={o.filePath} folder={o} level={level + 1}/> :
            <FileView key={o.filePath} file={o} level={level + 1}/>
        )) }
      </div>
    </div>
  );
}

function FileView (props: { file: IFile, level: number }) {
  const { file, level } = props;

  const onDoubleClick = (e: React.MouseEvent) => {
    if (!file.isLoaded) {
      appDispatch({
        // type: 'file.load',
        type: 'editor.open',
        data: file
      });
    }
  };

  return (
    <div className={cx('file-tree')}>
      <div className={cx('file-tree-name')} onDoubleClick={onDoubleClick} style={{paddingLeft: level * 16 + 5}}>
        <i className="icon-doc" style={{marginRight: 3}}></i>
        <span>{file.name}</span>
      </div>
    </div>
  );
}

export function FileExplorerView (props: { filesState: IFilesState }) {
  const { filesState } = props;
  const { folders } = filesState;

  return (
    <div className={cx('file-viewer')}>
      {folders.map(o => (
        <FolderView key={o.filePath} folder={o} level={0}/>
      ))}
    </div>
  );
}